<template>
  <ToolbarButton
    type="dropdown"
    icon="i-ri-list-ordered"
    title="有序列表"
    :active="isActive"
    dropdown-icon="i-ri-arrow-down-s-fill"
    popover-width="340px"
    popover-placement="bottom-start"
    @main-click="toggleOrderedList"
  >
    <template #dropdown>
      <div class="p-3 bg-white">
        <!-- 列表样式选择 - 使用6列网格布局以容纳更多选项 -->
        <div class="grid grid-cols-4 gap-2">
          <div
            v-for="style in listStyles"
            :key="style.value"
            @click="setOrderedList(style.value)"
            class="w-16 h-14 flex items-center justify-center text-xs border border-solid border-gray-300 rounded bg-white hover:bg-gray-100 transition-colors cursor-pointer"
            :style="
              currentStyle === style.value
                ? { borderColor: 'var(--editor-primary-color)' }
                : {}
            "
            :title="style.label"
          >
            <div class="flex flex-col gap-1.5 text-xs leading-tight">
              <div
                v-for="item in style.preview"
                :key="item.marker"
                class="flex items-center gap-1"
              >
                <span class="font-bold text-black text-[10px]">{{
                  item.marker
                }}</span>
                <div class="w-6 h-1 bg-gray-300 rounded"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>
  </ToolbarButton>
</template>

<script setup lang="ts">
import { inject, computed, ref, watch, onBeforeUnmount, type Ref } from "vue";
import type { Editor } from "@tiptap/vue-3";
import type { EditorProps } from "../../../../types";
import ToolbarButton from "../../../button/index.vue";
import { ORDERED_LIST_OPTIONS } from "../../../../config/constants";

defineOptions({
  name: "OrderedList",
});

// 注入编辑器实例和配置
const editor = inject<Ref<Editor>>("editor");
const editorProps = inject<EditorProps>("editorProps");

// 当前列表样式
const currentStyle = ref("decimal");

// 列表样式选项 - 从 EditorProps.dicts.orderedListStyles 获取，如果没有则使用默认值
const listStyles = computed(() => {
  const styles = editorProps?.dicts?.orderedListStyles || [];

  // 如果没有配置样式，使用默认样式列表
  if (styles.length === 0) {
    return ORDERED_LIST_OPTIONS;
  }

  return styles;
});

// 计算属性
const isActive = computed(() => {
  return editor?.value?.isActive("orderedList");
});

// 切换有序列表（主按钮点击）- 使用第一种样式
const toggleOrderedList = () => {
  if (!editor?.value) return;

  // 获取第一种样式作为默认样式
  const defaultStyle = listStyles.value[0]?.value || "decimal";

  const chain = editor.value.chain().focus();

  if (editor.value.isActive("orderedList")) {
    // 如果已经是有序列表，检查当前样式是否与默认样式相同
    const currentListType = editor.value.getAttributes("orderedList").listType;
    if (currentListType === defaultStyle) {
      // 如果样式相同，则切换为普通段落
      chain.toggleOrderedList().run();
    } else {
      // 如果样式不同，更新为默认样式
      chain.updateAttributes("orderedList", { listType: defaultStyle }).run();
      currentStyle.value = defaultStyle;
    }
  } else {
    // 创建有序列表并设置默认样式
    chain
      .toggleOrderedList()
      .updateAttributes("orderedList", { listType: defaultStyle })
      .run();
    currentStyle.value = defaultStyle;
  }
};

// 设置有序列表样式（下拉选项点击）
const setOrderedList = (listStyle: string) => {
  if (!editor?.value) return;

  currentStyle.value = listStyle;
  const chain = editor.value.chain().focus();

  if (editor.value.isActive("orderedList")) {
    // 如果已经是有序列表，检查当前样式是否与选择的样式相同
    const currentListType = editor.value.getAttributes("orderedList").listType;
    if (currentListType === listStyle) {
      // 如果样式相同，则切换为普通段落
      chain.toggleOrderedList().run();
    } else {
      // 如果样式不同，更新样式
      chain.updateAttributes("orderedList", { listType: listStyle }).run();
    }
  } else {
    // 创建有序列表并设置样式
    chain
      .toggleOrderedList()
      .updateAttributes("orderedList", { listType: listStyle })
      .run();
  }
};

// 监听编辑器变化，同步当前样式状态
watch(
  () => editor?.value,
  (newEditor, oldEditor) => {
    // 清理旧编辑器的事件监听
    if (oldEditor && (oldEditor as any)._orderedListHandler) {
      oldEditor.off("update", (oldEditor as any)._orderedListHandler);
      delete (oldEditor as any)._orderedListHandler;
    }

    if (newEditor) {
      // 监听编辑器更新，同步当前列表样式
      // 保存事件处理函数引用以便清理
      const updateHandler = () => {
        if (newEditor.isActive("orderedList")) {
          const listType = newEditor.getAttributes("orderedList").listType;
          if (listType) {
            currentStyle.value = listType;
          }
        }
      };
      newEditor.on("update", updateHandler);
      (newEditor as any)._orderedListHandler = updateHandler;
    }
  },
  { immediate: true }
);

// 组件卸载时清理事件监听器
onBeforeUnmount(() => {
  if (editor?.value && (editor.value as any)._orderedListHandler) {
    editor.value.off("update", (editor.value as any)._orderedListHandler);
    delete (editor.value as any)._orderedListHandler;
  }
});
</script>

<style scoped>
/* 只保留必要的悬停效果 */
.multilevel-list-item:hover {
  background-color: var(--editor-content-node-selected-background);
  border-radius: var(--editor-radius);
}
</style>
